'use strict';
const qs = require('qs');
const http = require('http');
const config = require('../../Config').tmnlHub;

function action(obj, cb) {
    let postData = qs.stringify({json: obj});
    let options = {
        hostname: config.host,
        port: config.port,
        path: '/remote_data',
        method: config.method,
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Content-Length': postData.length
        }
    };

    const req = http.request(options, (res) => {
        let queryRes = '';
        res.setEncoding('utf8');
        res.on('data', (chunk) => {
            queryRes += chunk;
        });
        res.on('end', () => {
            try {
                cb.call(null, JSON.parse(queryRes));
            } catch (e) {
                cb.call(null, {"error": true});
            }
        });
    });
    req.on('error', (e) => {
        let error = {"error": true, "message": e.code};
        cb.call(this, error);
    });
    req.write(postData);
    req.end();

}

module.exports = action;
